package weaver.interfaces.zhlx.duss.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.axis.encoding.Base64;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author dusongsong
 * @date 2023年08月21日 09:37
 */
public class SapUtil extends BaseBean {

    private static  JSONObject propVal = PropUtil.getPropVal("zhlxsap");
    private static  String URL = propVal.getString("url")+"/RESTAdapter/ec/interface";
    private static  String USERNAME = propVal.getString("username");
    private static  String PASSWORD = propVal.getString("password");

    /**
     * 请求处理器
     *
     * @param type
     * @param dataJson
     * @return
     */
    public JSONObject handleOKHttpRequest(String type, JSONObject dataJson, Map<String, Object> dataMap) {
        String fullDate = DateUtil.getFullDate();
        String curdate = fullDate.substring(0, 10).replace("-", "");
        String curtime = fullDate.substring(11, 19).replace(":", "");
        JSONObject headerJson = new JSONObject();
        headerJson.put("SYSID", "EC");
        headerJson.put("BUSINESS", type);
        headerJson.put("BUSNKEY", "YEJAJFHJDHKA");
        headerJson.put("TECHKEY", getUUIDStr().toUpperCase());
        headerJson.put("DATE", curdate);
        headerJson.put("TIME", curtime);
        JSONObject paramsJson = new JSONObject();
        JSONObject inuptJson = new JSONObject();
        inuptJson.put("HEADER", headerJson);
        inuptJson.put("DATA", dataJson);
        paramsJson.put("INPUT", inuptJson.toJSONString());
        JSONObject resultJson = sendOKHttpRequest(paramsJson);
        dataMap.put("jkqqcs", paramsJson);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap);
        return resultJson;
    }

    /**
     * 请求处理器
     *
     * @param type
     * @param dataList
     * @return
     */
    public JSONObject handleOKHttpRequest(String type, JSONArray dataList, Map<String, Object> dataMap) {
        String fullDate = DateUtil.getFullDate();
        String curdate = fullDate.substring(0, 10).replace("-", "");
        String curtime = fullDate.substring(11, 19).replace(":", "");
        JSONObject headerJson = new JSONObject();
        headerJson.put("SYSID", "EC");
        headerJson.put("BUSINESS", type);
        headerJson.put("BUSNKEY", "YEJAJFHJDHKA");
        headerJson.put("TECHKEY", getUUIDStr().toUpperCase());
        headerJson.put("DATE", curdate);
        headerJson.put("TIME", curtime);
        JSONObject paramsJson = new JSONObject();
        JSONObject inuptJson = new JSONObject();
        inuptJson.put("HEADER", headerJson);
        inuptJson.put("DATA", dataList);
        paramsJson.put("INPUT", inuptJson.toJSONString());
        JSONObject resultJson = sendOKHttpRequest(paramsJson);
        dataMap.put("jkqqcs", paramsJson);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap);
        return resultJson;
    }

    /**
     * 请求处理器
     *
     * @param type
     * @param dataJson
     * @return
     */
    public JSONObject handleOKHttpRequestNotLog(String type, JSONObject dataJson,String busnkey) {
        String fullDate = DateUtil.getFullDate();
        String curdate = fullDate.substring(0, 10).replace("-", "");
        String curtime = fullDate.substring(11, 19).replace(":", "");
        JSONObject headerJson = new JSONObject();
        headerJson.put("SYSID", "EC");
        headerJson.put("BUSINESS", type);
        headerJson.put("BUSNKEY", busnkey);
        headerJson.put("TECHKEY", getUUIDStr().toUpperCase());
        headerJson.put("DATE", curdate);
        headerJson.put("TIME", curtime);
        JSONObject paramsJson = new JSONObject();
        JSONObject inuptJson = new JSONObject();
        inuptJson.put("HEADER", headerJson);
        inuptJson.put("DATA", dataJson);
        paramsJson.put("INPUT", inuptJson.toJSONString());
        return sendOKHttpRequest(paramsJson);
    }

    /**
     * 发起请求
     *
     * @param params
     * @return
     */
    private JSONObject sendOKHttpRequest(JSONObject params) {
        JSONObject resultJson = new JSONObject();
        String code = "failure";
        String message = "";
        try {
            String authorization = " Basic " + Base64.encode((USERNAME + ":" + PASSWORD).getBytes());
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params.toJSONString());
            Request request = new Request.Builder()
                    .url(URL)
                    .method("POST", body)
                    .addHeader("Authorization", authorization)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                resultJson = JSONObject.parseObject(result);
                code = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("message", message);
        return resultJson;
    }

    /**
     * 获取uuid
     *
     * @return
     */
    public String getUUIDStr() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replace("-", "");
    }

    //根据表单和字段获取下拉框值
    public String getSelectname(int billid, String fieldname, String selectvalue) {
        RecordSet rs = new RecordSet();
        String sql = "select t1.selectvalue,t1.selectname from workflow_selectitem t1 left join workflow_billfield t2\n" +
                " on t1.fieldid=t2.id where abs(t2.billid)=? and t2.fieldname=? and t1.selectvalue=?";
        rs.executeQuery(sql, billid, fieldname, selectvalue);
        rs.next();
        return Util.null2String(rs.getString("selectname"));
    }

    /**
     * 返回yyyy-MM-dd
     *
     * @param datestr
     * @return
     */
    public static String formatDateToOA(String datestr) {
        String formatTime = "";
        if (!"".equals(datestr) && Util.getIntValue(datestr, -1) > 0) {
            try {
                SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd");
                Date date1 = date.parse(datestr);
                formatTime = new SimpleDateFormat("yyyy-MM-dd").format(date1);
            } catch (ParseException e) {
                formatTime = datestr;
            }
        }
        return formatTime;
    }

    /**
     * 返回yyyyMMdd
     *
     * @param datestr
     * @return
     */
    public static String formatDateToSAP(String datestr) {
        String formatTime = "";
        if (!"".equals(datestr) && Util.getIntValue(datestr, -1) < 0) {
            try {
                SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
                Date date1 = date.parse(datestr);
                formatTime = new SimpleDateFormat("yyyyMMdd").format(date1);
            } catch (ParseException e) {
                formatTime = datestr;
            }
        }
        return formatTime;
    }

    /**
     * 插入接口日志
     *
     * @param dataMap
     */
    private static void insertApiLog(Map<String, Object> dataMap) {
        String fullDate = DateUtil.getFullDate();
        try {
            InetAddress address = InetAddress.getLocalHost();
            String serverIp = address.getHostAddress();
            dataMap.put("fwqdz", serverIp);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        dataMap.put("jkqqdz", URL);
        dataMap.put("jkdysj", fullDate);
        dataMap.put("jktgf", "SAP");
        insertModelData("uf_apilog", 1, dataMap);
    }

    //建模权限重构
    private static void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    //将数据插入表单建模
    public static int insertModelData(String tablename, int userid, Map<String, Object> map) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        try {
            String sql = "select a.id from modeinfo a left join workflow_bill b on a.formid=b.id where b.tablename=?";
            rs.executeQuery(sql, tablename);
            rs.next();
            int modeid = Util.getIntValue(rs.getString("id"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
            Object[] params = {uuid, userid, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
            if (rs.executeUpdate(insSql, params)) {
                rs1.executeQuery("select id from " + tablename + " where modeuuid=?", uuid);
                rs1.next();
                dataid = Util.getIntValue(rs1.getString("id"));
                if (dataid > 0) {
                    //遍历数据 进行update
                    String updatesql = "update " + tablename + " set ";
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        if("jkqqcs".equals(key) && Util.null2String(map.get(key)).length()>4000){
                            updatesql += key + "='" + map.get(key).toString().substring(0,4000) + "',";
                        }else {
                            updatesql += key + "='" + map.get(key).toString() + "',";
                        }
                    }
                    if (updatesql.endsWith(",")) {
                        updatesql = updatesql.substring(0, updatesql.length() - 1);
                        updatesql += " where id=" + dataid;
                        rs.executeUpdate(updatesql);
                    }
                    //进行权限重构
                    newModeRight(userid, modeid, dataid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataid;
    }

    /**
     * 获取本币金额
     *
     * @return
     */
    public static String getbbje(String wbbb, String wbje) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select (hl/wbsl) from uf_saphlb where wbbb=? and bbbb='CNY' order by sxrq desc", wbbb);
        rs.next();
        String hl = Util.null2String(rs.getString(1));
        return fMultiply(hl, wbje, 2);
    }

    // 乘法保留小数位
    public static String fMultiply(String a, String b, int n) {
        a = isZero(a);
        b = isZero(b);
        BigDecimal bg1 = new BigDecimal(a);
        BigDecimal bg2 = new BigDecimal(b);
        BigDecimal bd = bg1.multiply(bg2).setScale(n, BigDecimal.ROUND_HALF_UP);
        return bd.toString();
    }

    public static String isZero(String a) {
        if ("".equals(a)) {
            a = "0";
        }
        return a;
    }

    public static String getBillFieldId(String tablename) {
        String strs = "";
        RecordSet rs = new RecordSet();
        String sql = "select a.fieldname from workflow_billfield a join workflow_bill b on a.billid=b.id " +
                "where b.tablename =? and b.detailkeyfield='mainid'";
        rs.executeQuery(sql, tablename);
        while (rs.next()) {
            String fieldname = Util.null2String(rs.getString(1));
            strs += "".equals(strs) ? fieldname : "," + fieldname;
        }
        return strs;
    }
}
